HttpsURLConnection ignore SSL Certificate Error / Accept all Certificate

Categories: Java; Tagged with: ; @ April 2nd, 2014 22:47

Requirement:  HttpsURLConnection ignore SSL Certificate Error / Accept all Certificate

package com.test;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public final class SSLUtils {
        
	public static void trustCertificate () throws KeyManagementException, NoSuchAlgorithmException {
        System.setProperty ( "https.protocols", "SSLv3" );     
        
		TrustManager[] trustAllCerts = new TrustManager[] { 
        	new X509TrustManager() {
				@Override
				public void checkClientTrusted(X509Certificate[] arg0,
						String arg1) throws CertificateException {
					System.out.println ( "checkClientTrusted()" );
				}
				@Override
				public void checkServerTrusted(X509Certificate[] arg0,
						String arg1) throws CertificateException {
					System.out.println ( "checkServerTrusted()" );
					
				}
				@Override
				public X509Certificate[] getAcceptedIssuers() {
					System.out.println ( "X509Certificate()" );
					return new X509Certificate[0];
				}
        	}
        };
		final SSLContext sc = SSLContext.getInstance("SSLv3");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());      
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier ( new HostnameVerifier () {

			@Override
			public boolean verify(String arg0, SSLSession arg1) {
				return true;
			}               
        } );
  }
	
}

 

Usage:

before url.openConnection() call trustCertificate ();

<->



// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.